<?php

class ConfigController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array(''),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array(''),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('index','view','create','update','admin','preparedatafile','generatesql','executesql1','executesql2','finishdatafile'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Config;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Config']))
		{
			$model->attributes=$_POST['Config'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Config']))
		{
			$model->attributes=$_POST['Config'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Config');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Config('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Config']))
			$model->attributes=$_GET['Config'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Config::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='config-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
        
        public function actionPrepareDataFile() {
            $this->render('prepareDataFile');    
        }
        
        public function actionGenerateSQL()
	{
            //$horaIni = date("H:i:s");
            //echo $horaIni;
            set_time_limit(220);
            if(file_exists("images/backup/tanai.sql")){
                $nombre_fichero = "images/backup/tanai.sql";
                $nombre_fichero_salida_1 = "images/backup/tanai_out_1.sql";
                $nombre_fichero_salida_2 = "images/backup/tanai_out_2.sql";
                $fichero_texto = fopen($nombre_fichero, "r");
                $fichero_texto_out_1 = fopen($nombre_fichero_salida_1, "w");
                $fichero_texto_out_2 = fopen($nombre_fichero_salida_2, "w");
                fwrite($fichero_texto_out_1, "insert into `tanai_product_master` values\r\n");
                fwrite($fichero_texto_out_2, "insert into `tanai_product_master` values\r\n");
                $data = 0;
                while (!feof($fichero_texto)) {
                    $line = substr(fgets($fichero_texto),0,-2);
                    if($data != 0){
                        if(strpos($line, "'0','0','0','0','0','0','0','0','0','0','0','0','0'") == false){
                            if(strpos($line, "SILVER") == true or strpos($line, "STEEL") == true){//No es plata o acero
                                $line = $line."\r\n";//TODO validar si en linux solo se necesita \n y no \r\n q es para windows
                                if($data < 9500){
                                    fwrite($fichero_texto_out_1, $line);    
                                } else {
                                    fwrite($fichero_texto_out_2, $line);
                                }
                                $data++;
                            }
                        }
                    } else {
                        $subLine = substr($line,0,6);
                        if(strcmp($subLine,"insert") == 0){
                            $data = 1;
                        }
                    }
                }
                //echo ' - Fin - ';//Fin
                //$horaFin = date("H:i:s");
                //echo $horaFin;
                //echo '<br />'.date("H:i:s", strtotime("00:00:00") + strtotime($horaFin) - strtotime($horaIni));
                fclose($fichero_texto);
                fclose($fichero_texto_out_1);
                fclose($fichero_texto_out_2);
                $this->render('executeSQL',array('ok'=>1));
            }else{
                $this->render('prepareDataFile',array('error'=>1));
            }
        } 
        
        public function actionExecuteSQL1()
	{
//            $horaIni = date("H:i:s");
//            echo $horaIni;
            $part = 1;
            set_time_limit(220);
            //super optimizado 48s 18mil reg
            if(file_exists("images/backup/tanai_out_".$part.".sql")){
                if($part == 1){
                    $sql = "TRUNCATE TABLE `tanai_product_master`;";
                    Yii::app()->db->createCommand($sql)->query();    
                }
                $nombre_fichero = "images/backup/tanai_out_".$part.".sql";
                $fichero_texto = fopen($nombre_fichero, "r");
                $data = false;
                while (!feof($fichero_texto)) {
                    $line = substr(fgets($fichero_texto),0,-2);
                    if($data){
                        if($line != '') {
                            $sql = "insert into `tanai_product_master` values ".$line.";";
                            Yii::app()->db->createCommand($sql)->query();
                        }
                    } else {
                        $subLine = substr($line,0,6);
                        if(strcmp($subLine,"insert") == 0){
                            $data = true;
                        }
                    }
                }
//                echo ' - Fin - ';//Fin
//                $horaFin = date("H:i:s");
//                echo $horaFin;
//                echo '<br />'.date("H:i:s", strtotime("00:00:00") + strtotime($horaFin) - strtotime($horaIni));
                fclose($fichero_texto);
                $this->render('executeSQL',array('ok'=>2));
            } else {
                $this->render('executeSQL',array('error'=>1));
            }    
        }
        
        public function actionExecuteSQL2()
	{
//            $horaIni = date("H:i:s");
//            echo $horaIni;
            $part = 2;
            set_time_limit(220);
            //super optimizado 48s 18mil reg
            if(file_exists("images/backup/tanai_out_".$part.".sql")){
                $nombre_fichero = "images/backup/tanai_out_".$part.".sql";
                $fichero_texto = fopen($nombre_fichero, "r");
                $data = false;
                while (!feof($fichero_texto)) {
                    $line = substr(fgets($fichero_texto),0,-2);
                    if($data){
                        if($line != '') {
                            $sql = "insert into `tanai_product_master` values ".$line.";";
                            Yii::app()->db->createCommand($sql)->query();
                        }
                    } else {
                        $subLine = substr($line,0,6);
                        if(strcmp($subLine,"insert") == 0){
                            $data = true;
                        }
                    }
                }
//                echo ' - Fin - ';//Fin
//                $horaFin = date("H:i:s");
//                echo $horaFin;
//                echo '<br />'.date("H:i:s", strtotime("00:00:00") + strtotime($horaFin) - strtotime($horaIni));
                fclose($fichero_texto);
                $this->render('finishDataFile');
            } else {
                $this->render('executeSQL',array('error'=>1));
            }    
        }
}
